import 'package:flutter/material.dart';
import 'package:imitatectripapp/dao/travel_dao.dart';
import 'package:imitatectripapp/model/travel_model.dart';
import 'package:flutter_staggered_grid_view/flutter_staggered_grid_view.dart';
import 'package:imitatectripapp/widget/loading_container.dart';
import 'package:imitatectripapp/widget/show_toast.dart';
import 'package:imitatectripapp/widget/webview.dart';

const PAGE_SIZE = 10;
const _TRAVEL_URL =
    'https://m.ctrip.com/restapi/soa2/16189/json/searchTripShootListForHomePageV2?_fxpcqlniredt=09031014111431397988&__gw_appid=99999999&__gw_ver=1.0&__gw_from=10650013707&__gw_platform=H5';

class TravelTabPage extends StatefulWidget {
  final String travelUrl;
  final String groupChannelCode;

  const TravelTabPage({Key key, this.travelUrl, this.groupChannelCode})
      : super(key: key);
  @override
  _TravelTabPageState createState() => _TravelTabPageState();
}

class _TravelTabPageState extends State<TravelTabPage>
    with AutomaticKeepAliveClientMixin {
  List<TravelItem> travelItems;
  int pageIndex = 1;

  // 加载进度条变量
  bool _loading = true; //刚进入页面的时候需要进行网络加载，我们默认显示true

  // 上拉加载更多实现
  ScrollController _scrollController = ScrollController();
  @override
  void initState() {
    // TODO: implement initState
    // 首次加载
    _loadData();
    // 监听滚动
    _scrollController.addListener(() {
      if (_scrollController.position.pixels ==
          _scrollController.position.maxScrollExtent) {
        // 上拉接口的数据请求
        _loadData(loadMore: true);
      }
    });
    super.initState();
  }

  // 销毁的声明周期
  @override
  void dispose() {
    // TODO: implement dispose
    _scrollController.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
        body: MediaQuery.removeViewPadding(
      context: context,
      removeTop: true,
      child: LoadingContainer(
          isLoading: _loading,
          child: RefreshIndicator(
            onRefresh: _handleRefresh,
            child: StaggeredGridView.countBuilder(
              controller: _scrollController,
              crossAxisCount: 4, //总共占几列
              itemCount: travelItems?.length ?? 0,
              itemBuilder: (BuildContext context, int index) =>
                  _TravelItemContanier(index: index, item: travelItems[index]),
              staggeredTileBuilder: (int index) =>
                  StaggeredTile.fit(2), //每个item占据其中的两列
            ),
          )),
    ));
  }

  // 接口数据的请求
  void _loadData({loadMore = false}) { //{}这是可选参数
    if (loadMore) {
      pageIndex++;
    } else {
      pageIndex = 1;
    }
    try {
      TravelDao.GETTravelData(widget.travelUrl ?? _TRAVEL_URL,
              widget.groupChannelCode, pageIndex, PAGE_SIZE)
          .then((TravelItemModel model) {
        _loading = false;
        setState(() {
          if(model.resultList.length == 0){
            ShowToast.toast(context,msg: '没有更多了',position: ToastPostion.bottom);
          }
          List<TravelItem> items = _filterItems(model.resultList);
          if (travelItems != null) {
            travelItems.addAll(items);
          } else {
            travelItems = items;
          }
        });
      }).catchError((e) {
        _loading = false;
        print(e);
      });
    } catch (e) {
      print(e);
    }
  }

  // 接口数据的过滤
  List<TravelItem> _filterItems(List<TravelItem> resultList) {
    if (resultList == null) {
      return [];
    }
    List<TravelItem> filterItems = [];
    resultList.forEach((item) {
      if (item.article != null) {
        //移出服务端返回的数据article为空的情况
        filterItems.add(item);
      }
    });
    return filterItems;
  }

  @override
  // TODO: implement wantKeepAlive
  bool get wantKeepAlive => true;

// 下拉刷新
  Future<Null> _handleRefresh() async {
    await Future.delayed(Duration(seconds: 2));
    // 数据请求
    _loadData();
    return null;
  }
}

// 创建瀑布流中的每一项
class _TravelItemContanier extends StatelessWidget {
  final TravelItem item;
  final int index;

  const _TravelItemContanier({Key key, this.item, this.index})
      : super(key: key);

  @override
  Widget build(BuildContext context) {
    return GestureDetector(
      onTap: () {
        if (item.article.urls != null && item.article.urls.length > 0) {
          Navigator.push(
              context,
              MaterialPageRoute(
                  builder: (context) => WebView(
                        url: item.article.urls[0].h5Url,
                        title: '详情',
                      )));
        }
      },
      child: Card(
        child: PhysicalModel(
          color: Colors.transparent,
          clipBehavior: Clip.antiAlias,
          borderRadius: BorderRadius.circular(5),
          child: Column(
            crossAxisAlignment: CrossAxisAlignment.start,
            children: <Widget>[
              // 图片区域
              _itemImage(),
              // 文字标题区域
              Container(
                padding: EdgeInsets.all(4),
                child: Text(
                  item.article.articleTitle,
                  maxLines: 2,
                  overflow: TextOverflow.ellipsis,
                  style: TextStyle(fontSize: 14, color: Colors.black87),
                ),
              ),
              // 用户信息区域
              _infoText()
            ],
          ),
        ),
      ),
    );
  }

  _itemImage() {
    return Stack(
      children: <Widget>[
        Image.network(item.article.images[0]?.dynamicUrl),
        Positioned(
          bottom: 8,
          left: 8,
          child: Container(
            padding: EdgeInsets.fromLTRB(5, 1, 5, 1),
            decoration: BoxDecoration(
                color: Colors.black54, borderRadius: BorderRadius.circular(10)),
            child: Row(
              children: <Widget>[
                Padding(
                  padding: EdgeInsets.only(right: 3),
                  child: Icon(
                    Icons.location_on,
                    color: Colors.white,
                    size: 12,
                  ),
                ),
                LimitedBox(
                  maxWidth: 130,
                  child: Text(
                    _posName(),
                    maxLines: 1,
                    overflow: TextOverflow.ellipsis,
                    style: TextStyle(color: Colors.white, fontSize: 12),
                  ),
                )
              ],
            ),
          ),
        )
      ],
    );
  }

  // 图片上的位置标志
  String _posName() {
    return item.article.pois == null || item.article.pois.length == 0
        ? '未知'
        : item.article.pois[0]?.poiName ?? '未知';
  }

  _infoText() {
    return Container(
      padding: EdgeInsets.fromLTRB(6, 0, 6, 10),
      child: Row(
        mainAxisAlignment: MainAxisAlignment.spaceBetween,
        children: <Widget>[
          Row(
            children: <Widget>[
              // 头像
              PhysicalModel(
                color: Colors.transparent,
                clipBehavior: Clip.antiAlias,
                borderRadius: BorderRadius.circular(12),
                child: Image.network(
                    item.article.author?.coverImage?.dynamicUrl,
                    width: 24,
                    height: 24),
              ),
              Container(
                padding: EdgeInsets.all(5),
                child: Text(
                  item.article.author?.nickName,
                  maxLines: 1,
                  overflow: TextOverflow.ellipsis,
                  style: TextStyle(fontSize: 12),
                ),
              )
            ],
          ),
          Row(
            children: <Widget>[
              Icon(Icons.thumb_up, size: 14, color: Colors.grey),
              Padding(
                padding: EdgeInsets.only(left: 3),
                child: Text(
                  item.article.likeCount.toString(),
                  style: TextStyle(fontSize: 10),
                ),
              )
            ],
          )
        ],
      ),
    );
  }
}
